import 'package:fig/sqlite/sql_manager.dart';
import 'package:sqflite_common/sqlite_api.dart';

class TableMediaActor extends TableBase {
  // 表名
  final String tableName = 'media_actor';
  static final String columnName = "name";

  Future<void> insertAllWithMediaId(int mediaId, String actors, int roleType, {Database database}) async {
    if (database == null) {
      database = await SqlManager.getCurrentDatabase();
    }

    if (actors == null || actors == "") {
      return;
    }

    var actorList = actors.split(',');
    for (String actor in actorList) {
      if (actor == null || actor == "") {
        continue;
      }
      final actorId = await install(mediaId, actor, database: database);
      installMap(mediaId, actorId, roleType, database: database);
    }
  }

  // 保存演员信息
  Future<int> install(int mediaId, String actor, {Database database}) async {
    var existActorList = await database.query(tableName, where: '$columnName=?', whereArgs: [actor]);
    var actorId = 0;
    if (existActorList.length == 0) {
      actorId = await database.insert(tableName, {
        '$columnName': actor,
        '${TableBase.columnCreateTime}': DateTime.now().millisecondsSinceEpoch,
      });
    } else {
      actorId = existActorList[0]['${TableBase.columnId}'];
    }
    return actorId;
  }

  // 保存影视关联信息
  Future<void> installMap(int mediaId, int actorId, int roleType, {Database database}) async {
    var existActorMapList = await database.query(
      TableMediaActorMap.tableName,
      where: '${TableMediaActorMap.columnMediaId}=? and ${TableMediaActorMap.columnActorId}=? and ${TableMediaActorMap.columnRoleType}=?',
      whereArgs: [mediaId, actorId, roleType],
    );

    if (existActorMapList.length == 0) {
      database.insert(TableMediaActorMap.tableName, {
        '${TableMediaActorMap.columnMediaId}': mediaId,
        '${TableMediaActorMap.columnActorId}': actorId,
        '${TableMediaActorMap.columnRoleType}': roleType,
        '${TableBase.columnCreateTime}': DateTime.now().millisecondsSinceEpoch,
      });
    }
  }

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnName text,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}

class TableMediaActorMap extends TableBase {
  // 表名
  static final String tableName = 'media_actor_map';
  static final String columnActorId = "actor_id";
  static final String columnRoleType = "role_type"; // 角色类型 0演员 1导演
  static final String columnMediaId = "media_id";

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnActorId integer,
    $columnRoleType integer,
    $columnMediaId integer,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}
